package com.ja.openchat.ui.chat.group;

import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.listener.OnLoadMoreListener;
import com.google.gson.JsonObject;
import com.ja.openchat.BR;
import com.ja.openchat.R;
import com.ja.openchat.databinding.FragmentListBinding;
import com.ja.openchat.ui.chat.FileDisplayActivity;
import com.ja.openchat.ui.chat.MessageViewModel;
import com.ja.openchat.ui.chat.PreviewMediaActivity;
import com.ja.openchat.ui.chat.PreviewWebViewActivity;
import com.ja.openchat.ui.chat.audio.AudioPlayManager;
import com.ja.openchat.ui.chat.audio.IAudioPlayListener;
import com.ja.openchat.ui.chat.group.adapter.GroupSettingChildAdapter;
import com.ja.openchat.ui.chat.group.adapter.GroupSettingOfMembersAdapter;
import com.ja.openchat.viewmodels.GroupSettingChildViewModel;
import com.ja.openchat.viewmodels.GroupSettingViewModel;
import com.ja.openchat.views.AppFileReaderView;
import com.zy.openchat.App;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.file.DocumentInfo;
import com.zy.openchat.core.model.group.GroupMemberInfo;
import com.zy.openchat.core.model.message.ChatInfo;
import com.zy.openchat.core.model.message.MessageInfo;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import me.goldze.mvvmhabit.base.BaseFragment;

public class GroupSettingChildFragmentNew extends BaseFragment<FragmentListBinding, GroupSettingChildViewModel> {


    private static final int MESSAGE_LOAD_AROUND = 50;
    private long focusMessageId = 0;
    public int pageIndex = 0;
    private GroupSettingViewModel groupSettingViewModel;

    private ChatInfo conversation;

    public static GroupSettingChildFragmentNew newInstance(int position, ChatInfo chatInfo){
        GroupSettingChildFragmentNew fragment = new GroupSettingChildFragmentNew();
        Bundle bundle = new Bundle();
        bundle.putParcelable("chat",chatInfo);
        bundle.putInt("position",position);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_list;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public void initView() {
        super.initView();
        viewModel.setFragment(this);
        initDataAndEvent();
    }

    protected void initDataAndEvent() {
        if(getArguments()!=null){
            pageIndex = getArguments().getInt("position");
            conversation = getArguments().getParcelable("chat");
        }

        if(pageIndex ==0){
            wrapperMembers();
        }else{
            wrapperMessages();
        }
    }

    private void requestChatData(){
        TelegramManager.getTelegramManager().getChatMessageList(getContext(),conversation.id, focusMessageId, 0, MESSAGE_LOAD_AROUND, new TgResultBlock<List<MessageInfo>>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, List<MessageInfo> obj) {
                if(obj!=null&&obj.size()>0){
                    List<MessageInfo> messages = new ArrayList<>();
                    for(MessageInfo messageInfo:obj){
                        if(isMatch(messageInfo)){
                            messages.add(0,messageInfo);
                        }
                    }
                    focusMessageId = obj.get(0).id;
                    if(focusMessageId==0){
                        messageAdapter.setNewData(messages);
                    }else{
                        messageAdapter.addData(messages);
                    }
                    messageAdapter.getLoadMoreModule().loadMoreComplete();
                    if(messages.size()==0){
                        requestChatData();
                    }
                }else{
                    messageAdapter.getLoadMoreModule().loadMoreEnd();
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                messageAdapter.getLoadMoreModule().loadMoreEnd();
            }
        });
    }

    private boolean isMatch(MessageInfo messageInfo){
        if(pageIndex ==1){
            return messageInfo.messageType == TelegramManager.MessageType.MessageType_Photo||messageInfo.messageType == TelegramManager.MessageType.MessageType_Video;
        }else if(pageIndex ==2){
            return messageInfo.messageType == TelegramManager.MessageType.MessageType_Document;
        }else if(pageIndex ==3){
            return messageInfo.messageType == TelegramManager.MessageType.MessageType_Audio;
        }else if(pageIndex ==4){
            return messageInfo.messageType == TelegramManager.MessageType.MessageType_Text && MessageViewModel.isLinkString(messageInfo.textTypeContent);
        }else{
            return messageInfo.messageType == TelegramManager.MessageType.MessageType_Animation;
        }
    }

    private GroupSettingChildAdapter messageAdapter;
    private void wrapperMessages(){
        binding.recyclerView.setLayoutManager(new GridLayoutManager(getContext(),3));
        messageAdapter = new GroupSettingChildAdapter();
        binding.recyclerView.setAdapter(messageAdapter);
        viewModel.setAdapter(conversation,messageAdapter);
        messageAdapter.getLoadMoreModule().setEnableLoadMore(true);
        messageAdapter.getLoadMoreModule().setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                requestChatData();
            }
        });
        messageAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
                MessageInfo messageInfo = messageAdapter.getItem(position);
                if(pageIndex == 1){
                    PreviewMediaActivity.previewMedia(getContext(),messageAdapter.getData(),position);
                }else if(pageIndex == 2){
                    if(messageInfo.content!=null&&messageInfo.content.document!=null){
                        DocumentInfo documentInfo = messageInfo.content.document;
                        if(!documentInfo.isFileDownloaded()){
                            ToastUtils.showShort(getString(R.string.file_downloading_text));
                            TelegramManager.getTelegramManager().downloadFile(messageInfo.chat_id+"_" + messageInfo.id, documentInfo.document.id, 0, TelegramManager.FileType.FileType_Message_Document);
                            return;
                        }
                        if(DocumentInfo.isImageFile(documentInfo.file_name)||DocumentInfo.isVideoFile(documentInfo.file_name)){
                            PreviewMediaActivity.previewImage(getContext(),messageInfo);
                        }else{
                            String fileExtension = AppFileReaderView.getFileType(documentInfo.file_name);
                            FileDisplayActivity.startActivity(getContext(),documentInfo.localFilePath(),fileExtension);
                        }
                    }
                }else if(pageIndex == 3){
                    if (!messageInfo.isAudioFileDownloaded()) {
                        TelegramManager.getTelegramManager().downloadFile(messageInfo.chat_id+"_" + messageInfo.id, messageInfo.getAudioFileId(), 0, TelegramManager.FileType.FileType_Message_Audio);
                        ToastUtils.showShort(getString(R.string.file_downloading_text));
                        return;
                    }
                    File file = new File(messageInfo.audioLocalPath());
                    playAudio(messageInfo,file);
                }else if(pageIndex == 4){
                    String link = messageInfo.textTypeContent;
                    PreviewWebViewActivity.loadUrl(getContext(), "", link);
                }else{
                    PreviewMediaActivity.previewMedia(getContext(),messageAdapter.getData(),position);
                }
            }
        });
        requestChatData();
    }

    private void playAudio(MessageInfo message, File file) {
        Uri uri = Uri.fromFile(file);
        AudioPlayManager.getInstance().startPlay(App.getInstanse(), uri, new IAudioPlayListener() {
            @Override
            public void onStart(Uri var1, int lengthoftime) {
                if (uri.equals(var1)) {
                }
            }

            @Override
            public void onStop(Uri var1) {
                if (uri.equals(var1)) {

                }
            }

            @Override
            public void onProgress(Uri var1,int  currentPosition,int secendProssed, int totalLenght) {

            }

            @Override
            public void onComplete(Uri var1) {
                if (uri.equals(var1)) {

                }
            }
        });
    }


    private Observer<List<GroupMemberInfo>> groupMembersObserver ;
    private GroupSettingOfMembersAdapter groupSettingOfMembersAdapter;
    private void wrapperMembers(){
        groupSettingViewModel = ViewModelProviders.of(getActivity()).get(GroupSettingViewModel.class);
        binding.recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        groupSettingOfMembersAdapter = new GroupSettingOfMembersAdapter();
        groupSettingOfMembersAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
                GroupMemberInfo memberInfo = groupSettingOfMembersAdapter.getItem(position);
                if(memberInfo!=null&&getActivity()!=null&&getActivity() instanceof GroupChatSettingsNewActivity){
                    ((GroupChatSettingsNewActivity)getActivity()).clickMember(memberInfo,false);
                }
            }
        });
        binding.recyclerView.setAdapter(groupSettingOfMembersAdapter);
        viewModel.setgroupSettingOfMembersAdapter(groupSettingOfMembersAdapter);
        groupMembersObserver = new Observer<List<GroupMemberInfo>>() {

            @Override
            public void onChanged(List<GroupMemberInfo> groupMemberInfos) {
                groupSettingOfMembersAdapter.setNewData(groupMemberInfos);
            }
        };
        groupSettingViewModel.groupInfoLiveData().observeForever(groupMembersObserver);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if(groupMembersObserver!=null&&groupSettingViewModel!=null){
            groupSettingViewModel.groupInfoLiveData().removeObserver(groupMembersObserver);
        }
    }
}
